import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, In, Like } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateFeedbackDto, UpdateFeedbackDto, QueryFeedbackDto } from './dto/feedback.dto';
import { FeedbackEntity } from './entities/feedback.entity';
import { isEmpty } from 'src/common/utils';

@Injectable()
export class FeedbackService {
  constructor(
    @InjectRepository(FeedbackEntity)
    private readonly feedbackEntityRep: Repository<FeedbackEntity>,
  ) {}

  async create(createFeedbackDto: CreateFeedbackDto) {
    const res = await this.feedbackEntityRep.save(createFeedbackDto);
    return ResultData.ok(res);
  }

  async findAll(query: QueryFeedbackDto) {
    const entity = this.feedbackEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.id)) {
      entity.andWhere('entity.id = :id', { id: query.id });
    }
    if (!isEmpty(query.userId)) {
      entity.andWhere('entity.userId = :userId', { userId: query.userId });
    }
    if (!isEmpty(query.content)) {
      entity.andWhere('entity.content = :content', { content: query.content });
    }
    if (!isEmpty(query.screenshot)) {
      entity.andWhere('entity.screenshot = :screenshot', { screenshot: query.screenshot });
    }
    if (!isEmpty(query.delFlag)) {
      entity.andWhere('entity.delFlag = :delFlag', { delFlag: query.delFlag });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.createTime[0], end: query.createTime[1] });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', { start: query.updateTime[0], end: query.updateTime[1] });
    }
    entity.select(['entity.id', 'entity.userId', 'entity.content', 'entity.screenshot']);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(id: number) {
    const res = await this.feedbackEntityRep.findOne({
      where: {
        delFlag: '0',
        id: id,
      },
    });
    return ResultData.ok(res);
  }

  async update(updateFeedbackDto: UpdateFeedbackDto) {
    const res = await this.feedbackEntityRep.update({ id: updateFeedbackDto.id }, updateFeedbackDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async remove(ids: number[]) {
    const res = await this.feedbackEntityRep.update(
      { id: In(ids) },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }
}
